<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/8/2
 * Time: 17:36
 */

namespace app\wap\controller;

use app\api\controller\Common;
use app\api\controller\KbxOrder;
use think\Cookie;
use think\Exception;
use think\log;
use app\api\controller\Viator;
use app\wap\model\Order as M;
use think\Db;
use app\api\model\Fareharbor;
use think\Request;
use app\api\controller\Trip as TripApi;


class Order extends Basewap
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }

    public  $statusArr = array(
        '1' => array(
            'orderStatus' => 'pending',
            'paymentStatus' => 'pending',
        ),
        '2' => array(
//            'orderStatus' => 'toBeStarting',
            'orderStatus' => 'pending',
            'paymentStatus' => 'paid',
        ),
        '3' => array(
            'orderStatus' => 'finished',
            'paymentStatus' => 'paid',
        ),
        '4' => array(
            'orderStatus' => 'reviewed',
            'paymentStatus' => 'paid',
        ),
        '5' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'refunding',
        ),
        '6' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunding',
        ),
        '7' => array(
            'orderStatus' => 'expired',
            'paymentStatus' => 'pending',
        ),
        '8' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunded',
        ),
        '9' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'rejected',
        ),
        '10' => array(
            'orderStatus' => 'unknown',
            'paymentStatus' => 'pending',
        )
    );

    //下单
    public function index()
    {
        $m=new M();
        $post=request()->post();
        if($post['typesource']=='viator'){
            $count_peo=0;
            $reg="/成人/";
            foreach ($post['personArr'] as $a){
                $count_peo+=$a['person_num_buy'];
                if($a['person_num_buy']>$a['max']){
                    $shu=[
                        'code'=>101,
                        'msg'=>$a['person_name'].'的最大人数不超过'.$a['max'].'人',
                    ];
                    return json_encode($shu);
                }
                preg_match($reg,$a['person_name'],$aduit);
                if(count($aduit)>0 && $a['person_num_buy']==0){
                    $shu=[
                        'code'=>101,
                        'msg'=>'至少有一个成人!',
                    ];
                    return json_encode($shu);
                }
            }
            if($count_peo>9){
                $shu=[
                    'code'=>101,
                    'msg'=>'总人数不能超过9个！',
                ];
                return json_encode($shu);
            }elseif($count_peo==0){
                $shu=[
                    'code'=>101,
                    'msg'=>'至少有一个成人！',
                ];
                return json_encode($shu);
            }
        }

        if ($post['totalPrice']==0){
            $shu=[
                'code'=>101,
                'msg'=>'免费商品不能单独购买 价格为0 不能下单',
            ];
            echo json_encode($shu); die;
        }

        $pos=[];
        foreach ($post['personArr'] as $v){
            if ($v['person_num_buy']!=0){
                $minorder_num = isset($v['minorder_num']) ? $v['minorder_num'] : 1;
                if($v['person_num_buy']<$minorder_num){
                    $shu=[
                        'code'=>101,
                        'msg'=>'该商品当前种类最低下单数为'.$minorder_num,
                    ];
                    echo json_encode($shu); die;
                }
                $pos[]=[
                    'person_name'=>$v['person_name'],
                    'person_num'=>$v['person_num_buy'],
                    'person_price'=>$v['person_price'],
                    'person_cost'=>$v['total_cost']??0,
                    'chuxing'=>$post['buyDay'],
                    'person_id'=>$v['person_id'],
                    'minorder_num'=>$minorder_num
                ];
            }
        }

        //获取商品
        $goods=db('goods')->where('goods_id',$post['goods_id'])->find();


        //为fareharbor商品时，生成订单界面就去查询是否可订
        if($post['typesource']=='fareharbor'){
            $Fareharbor = new Fareharbor();
            $fare_goods = db('fareharbor_goods')->where('fare_goods_id',$goods['source_id'])->find();
            $dateGoods = $Fareharbor->date($fare_goods['company'],$fare_goods['item_id'],$post['buyDay']);
            if(empty($dateGoods)){//不可用
                $shu=[
                    'code'=>101,
                    'data'=>$dateGoods,
                    'msg'=>'该商品当前日期不可预订',
                ];
                echo json_encode($shu); die;
            }
        }

        $que=0;
        if ($goods['need_confirm']==1 ){
            if($goods['show']==2){
                $que=1;
            }else if($goods['show']==1){
                $que=3;
            }else{
                $que=1;
            }
        }

        $where['isdelete']=0;
        $where['order_status']=[['NEQ',6],['NEQ',7,'or']];//订单查询条件

        if ($post['typesource']=='myself'){
            $typesource='myself';
            //获取订单
            $maiqu= db('order')
                ->where('goods_id',$post['goods_id'])
                ->where($where)
                ->where('travel_date',$post['buyDay'])
                ->select();

            foreach ($maiqu as $k){
                if (empty($k['orderperson'])){
                    $shengyu=db('orderperson')->where('order_id',$k['order_id'])->select();
                }else{
                    $shengyu=json_decode($k['orderperson'],true);
                }
                $ce = db('person')//获取普通商品规格属性
                ->where('specs_id',$post['specs_id'])
                    ->where('person_status', 1)
                    ->select();

                foreach ($ce as $v){
                    foreach ($shengyu as $j){
                        if ($j['person_name'] === $v['person_name']){
                            foreach ($post['personArr'] as $s){
                                $person_num = $v['person_num'] - ($j['person_num']+$s['person_num_buy']);
                                if ($person_num<0){
                                    $tishi=$v['person_name'].'数量库存不足！';
                                    $shu=[
                                        'code'=>101,
                                        'msg'=>$tishi,
                                        'data'=>''
                                    ];
                                    echo json_encode($shu); die;
                                }
                            }
                        }
                    }
                }
            }
        }elseif($post['typesource']=='viator'){
            $typesource='viator';
        }elseif($post['typesource']=='fareharbor'){
            $typesource='fareharbor';
        }else{
            $typesource=$post['typesource'];
        }

        $mk=model('Marketing')//获取活动
            ->where('goods_id',$post['goods_id'])
            ->where('mk_status',1)
            ->find();

        $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //1.获取字符串的长度
        $length = strlen($str)-1;
        //2.字符串截取开始位置
        $start=rand(0,$length);
        //3.随机截取字符串，取其中的一部分字符串
        $A=substr($str, $start,1);
        $order_no=$A. date('Ymd').rand('5','99999');
        $shu=[];

        // 启动事务
        Db::startTrans();
        try{
            $mem=db('member')->where('member_id',$post['member_id'])->field('member_username,member_pcode')->find();
            if ($goods['show']==2){
                if ($goods['alltravellermessage']==1){
                    $order_ascription=3;
                }else{
                    $order_ascription=2;
                }
            }else{
                $order_ascription=1;
            }


            //*************************************************************************************
            //判断订单类型，决定是否调用订单系统接口，存订单系统mongo库还是本系统mysql
            if(in_array($goods['orderType'],array("Vehicle","Custom","Other","Rental_Device","Price_Gap","Self_Drive","Personal_Tailor","Subscription")))
            {//存mysql
                $order_id= $m->insertGetId([
                    'order_no'=>$order_no,
                    'goods_id'=>$post['goods_id'],//商品id
                    'member_id'=>$post['member_id'],//会员id
                    'original_money'=>$post['totalPrice'],//交易金额
                    'fold_money'=>$post['totalPrice'],//交易金额
                    'add_integral'=>$post['integral'],//购买获得的积分
                    'creattime'=>time(),//下单时间
                    'travel_date'=>$post['buyDay'],//出行时间
                    'totalnum'=>$post['totalNum'],//购买数量
                    'specs_id'=>$post['specs_id'],//规格id
                    'finished_condition'=>1,//完成状况
                    'member_pcode'=>!empty($mem['member_pcode'])?$mem['member_pcode']:null,//完成状况
                    'orderperson'=>json_encode($pos),//完成状况
                    'order_ascription'=>$order_ascription,//订单归属
                    'code'=>$goods['code'],//订单归属
                    'grade'=>$post['code'],//订单归属
                    'typesource'=>$typesource,
                    'grade_name'=>isset($post['gradeName']) ? $post['gradeName'] : '',//套餐名称
                    'speedstatus'=>$que,
                ]);

                $shu=[
                    'code'=>0,
                    'msg'=>'生成订单成功',
                    'data'=>[
                        'order_no'=>$order_no,
                        'order_id'=>$order_id,
                        "orderType"=>$goods['orderType'],//订单类型
                    ]
                ];
            }else{//存mongo
                //调用  订单系统creat接口
                $city=db('city')->where('id',$goods['city_id'])->find();

                $pname =  '';
                $pphone =  '';
                $premark =  '';
                if(isset($mem['member_pcode']) && !empty($mem['member_pcode'])){
                    $pmember = db("member")->where("member_id",$mem['member_pcode'])->find();
                    if(!empty($pmember)){
                        $pname =  $pmember['member_nickname'];
                        $pphone =  $pmember['member_phone'];
                        $premark =  $pmember['member_remark'];
                    }
                }

                $goods_code = $goods['code'];
                if($post['typesource']=='fareharbor'){
                    $item_fare = db("fareharbor_goods")
                        ->where("fare_goods_id",$goods['source_id'])
                        ->field("item_id")
                        ->find();
                    $goods_code = $item_fare['item_id'];
                }

                //组装数据
                $postArr = array(
                    "orderType" => $goods['orderType'],//订单类型
                    'typeSource' => $typesource,
                    'speedStatus'=> $que,//二次确认进度
                    'orderAscription'=> $order_ascription,//订单归属
                    'specsId' => $post['specs_id'],//规格id
                    "isSubmit" => '',//是否已提交
                    "isDelete" => 0,//是否删除
                    'goods' => array(//商品
                        "goodsId" => $post['goods_id'],
                        "totalnum" => $post['totalNum'],//购买数量
                        "code" => $goods_code,
                        'grade'=>$post['code'],//订单归属
                        "goodsName" => $goods['goods_name'],
                        "cityId" => $goods['city_id'],
                        "cityNameen" => $city['eng_name'],
                        "gradeName" => isset($post['gradeName']) ? $post['gradeName'] : '',//套餐名称
                        "fromCity" => $city['kbx_id']
                    ),
                    'booker'=> array(//预订人
                        "username" => $mem['member_username'],
                        "memberId" => $post['member_id'],//会员id
                        "memberPCode" => !empty($mem['member_pcode'])?$mem['member_pcode']:null,//推荐人id
                        "memberPName" => $pname,//推荐人昵称
                        "memberPPhone" => $pphone,//推荐人电话
                        "memberPRemark" => $premark,//推荐人备注
                    ),
                    'payments'=> array(//支付
                        "originalMoney" => $post['totalPrice'],//原价金额
                        'foldMoney'=>$post['totalPrice'],//交易金额
                        "addIntegral" => $post['integral'],//购买获得的积分
                    ),
                    'itinerary'=> array(//出行
                        "travelDate" => $post['buyDay'],//出行时间
                        "orderPerson" => $pos,//完成状况
                    ),
                    'statusPhp'=> array(//状态（旧）
                        "orderStatus" => 1,
                        "finishedCondition" => 1,
                        "updateStatus" => 0,
                    ),
                    'status'=>array(//状态（新）
                        'orderStatus'=>$this->statusArr[1]['orderStatus'],
                        'paymentStatus'=>$this->statusArr[1]['paymentStatus'],
                    )
                );
                if($goods['supplier_admin_id']){
                    $supplier_admin = (new Common())->getSupplierAdminInfo($goods['supplier_admin_id']);
                    if(!empty($supplier_admin['company_id'])){
                        $postArr['supplier']['supplier'] = $supplier_admin['company_id'];
                    }
                }
                //非供应商产品 不传成本参数
                if(empty($postArr['supplier']['supplier'])){
                    foreach ($postArr['itinerary']['orderPerson'] as $pos_v){
                        unset($pos_v['person_cost']);
                    }
                }

                $KbxOrder = new KbxOrder();
                $create_res = $KbxOrder->kbx_operate_order($goods['orderType'],$postArr);

                $log[]=[
                    '订单系统API：生成'=>json_encode($postArr),
                    'res'=>$create_res
                ];
                Log::record($log);

                $create_res_arr = json_decode($create_res,true);

                $shu=[
                    'code'=>0,
                    'msg'=>'生成订单成功',
                    'data'=>[
                        'order_no'=>$create_res_arr['orderNo'],
                        'order_id'=>$create_res_arr['id'],
                        "orderType"=>$goods['orderType'],//订单类型
                        "typesource"=>$typesource,//typesource
                    ]
                ];
            }

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $shu=[
                'code'=>400,
                'msg'=>$e->getMessage(),
                'error'=>$e->getMessage()
            ];
        }

        return json_encode($shu);
    }


    public function determine(){//确定订单
        $order_id = input('order_id');
        $orderType = input('orderType');
        $order_no = input('order_no');

        $shu=[];
        Db::startTrans();
        try{
            //判断订单类型，决定是否调用订单系统接口，存订单系统mongo库还是本系统mysql
            if(in_array($orderType,array("Vehicle","Custom","Other","Rental_Device","Price_Gap","Self_Drive","Personal_Tailor","Subscription")))
            {//mysql
                $m = new M();
                $order = $m
                    ->alias('o')
                    ->where('o.order_id',$order_id)
                    ->join('goods a','a.goods_id=o.goods_id')
                    ->field('a.goods_id,a.goods_name as poi_name,a.goods_image,o.travel_date,o.original_money,o.order_id,o.order_no,a.show,o.orderperson,o.order_ascription,o.typesource')
                    ->find();
                $img = !empty($order['goods_image'])?explode(',',$order['goods_image']):'';
                if (!empty($img[1])){
                    $order['goods_image']=$img[1] ;
                }
                $ren=[];
                if (empty($order['orderperson'])){
                    $ren=db('orderperson')->where('order_id',$order['order_id'])->field('id,person_name,person_num,cost_ticket_id as coupon_id')->select();
                }else{
                    $ren=json_decode($order['orderperson'],true);
                    unset($order['orderperson']);
                }
                $order['person']=$ren;
            }else{//mongo
                $KbxOrder = new KbxOrder();
                $kbx_order = $KbxOrder->kbx_order_by_no($order_no);
                $order = Db::name("goods")->where("goods_id",$kbx_order['goods']['goodsId'])->field('goods_name as poi_name,goods_image,show')->find();
                $img=  !empty($order['goods_image'])?explode(',',$order['goods_image']):'';
                if (!empty($img[1])){
                    $order['goods_image']=$img[1] ;
                }

                $order['travel_date'] = date('Y-m-d',strtotime($kbx_order['itinerary']['travelDate']));
                $order['original_money'] = $kbx_order['payments']['originalMoney'];
                $order['order_id'] = $order_id;
                $order['order_no'] = $order_no;
                $order['order_ascription'] = $kbx_order['orderAscription'];
                $order['typesource'] = $kbx_order['typeSource'];
                $order['person'] = $kbx_order['itinerary']['orderPerson'];
            }

            Db::commit();
            $shu=[
                'code'=>0,
                'msg'=>'查询成功',
                'data'=>$order
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $shu=[
                'code'=>0,
                'msg'=>'查询失败',
                'error'=>$e->getMessage()
            ];
        }
        return json_encode($shu);
    }



    //完善订单提交
    public function submit(){
        $post = request()->post();
        $orderType = $post['orderType'];
        $order_no = $post['order_no'];
        $order_id = $post['order_id'];

        $log[]=[
            'submit开始:'.$order_no => json_encode($post),
        ];
        Log::record($log);

        $data=[];
        $KbxOrder = new KbxOrder();
        $m = new M();

        //判断订单类型，决定是否调用订单系统接口，存订单系统mongo库还是本系统mysql
        if(in_array($orderType,array("Vehicle","Custom","Other","Rental_Device","Price_Gap","Self_Drive","Personal_Tailor","Subscription")))
        {//存mysql
            $od=$m->where('order_id',$post['order_id'])->find();
            $goods_id = $od['goods_id'];
            //调用计算价格
            //判断如果有msg 就抛出错误
            if (!empty($od['updatetime'])){
                $shu=[
                    'code'=>305,
                    'msg'=>"请不要重复提交订单，可进入‘我的’-‘我的订单’中支付该订单",
                ];
                return json_encode($shu);
                die;
            }
            if (!empty($post['coupon_id'])){
                $arr=[
                    'order_id' =>$post['order_id'],
                    'coupon_id'=>$post['coupon_id'],
                    'member_id'=>$post['member_id'],
                    'coupon_type'=>$post['coupon_type'],
                    'type'=>0,
                ];
                $jiage= $this->price($arr);
            }
            if (!empty($jiage['msg'])) return json_encode([ 'code'=>101, 'msg'=>$jiage['msg']]);
            $posts=[];
            $code= db('goods')->where('goods_id',$od['goods_id'])->find();
            $pos=json_decode($od['orderperson'] ,true);
            $data['order']=$od['order_no'];//订单流水
            $data['time']=$od['travel_date'];
            $data['code']=$code['code'];  //产品code
            $data['tourGradeCode']=$od['grade'];  //旅游等级 商品详情获取 tourGrades
            $data['orderuser']=[  //下单人信息- -
                'firstname'=>$post['contact_ming'],  //名
                'surname'=>$post['contact_xing'],  //姓
                'Phone'=>$post['phone'], //必填
                'email'=>$post['e_mail'],
                'title'=>'',
            ];
            foreach ($pos as $v){
                $datas['bandid'][$v['person_id']]= $v['person_num'];
            }
            if ($od['order_ascription']==2||$od['order_ascription']==3) {
                $ds=json_decode($post['person'],true);
                foreach ($ds as $v){
                    if ( $v['person_id']==1){
                        foreach ($v['people'] as $l=>$h){
                            if ($l==0){
                                $tempList=[  //领班人/领头人
                                    'leadTraveller'=>true,
                                    'bandId'=>$v['person_id'],
                                    'firstname'=>$h['ming'],
                                    'surname'=>$h['xing'],
                                    'title'=>'',//称呼
                                    'cellPhoneCountryCode'=>$h['phoneCode'],//手机国家码
                                    'cellPhone'=>$h['phone'],//手机
                                ];
                            }else{
                                $tempList=[  //领班人/领头人
                                    'leadTraveller'=>false,
                                    'bandId'=>$v['person_id'],
                                    'firstname'=>$h['ming'],
                                    'surname'=>$h['xing'],
                                    'title'=>'',//称呼
                                    'cellPhoneCountryCode'=>'',//手机国家码
                                    'cellPhone'=>'',//手机
                                ];
                            }
                            $data['bandiduser'][]=$tempList;
                        }
                    }else{
                        foreach ($v['people'] as $l=>$h) {
                            $tempList = [  //领班人/领头人
                                'leadTraveller' => false,
                                'bandId' => $v['person_id'],
                                'firstname' => $h['ming'],
                                'surname' => $h['xing'],
                                'title' => '',//称呼
                                'cellPhoneCountryCode' => '',//手机国家码
                                'cellPhone' => '',//手机
                            ];
                        }
                        $data['bandiduser'][]=$tempList;
                    }
                }
            }
        }else{//存mongo
            //获取订单信息
            $kbx_order = $KbxOrder->kbx_order_by_no($order_no);
            $goods_id = $kbx_order['goods']['goodsId'];
            $typeSource = $kbx_order['typeSource'];

            if ($kbx_order['isSubmit']=='submit'){
                $shu=[
                    'code'=>305,
                    'msg'=>"请不要重复提交订单，可进入‘我的’-‘我的订单’中支付该订单",
                ];
                return json_encode($shu);
                die;
            }

            //当订单为fareharbor商品时，验证是否可成单
            if($typeSource=='fareharbor'){
                $Fareharbor = new Fareharbor();
                $goods = db("goods")->where("goods_id",$goods_id)->field("source_id")->find();
                $fare_goods = db('fareharbor_goods')->where('fare_goods_id',$goods['source_id'])->find();

                $orderPerson = $kbx_order['itinerary']['orderPerson'];

                $customerArr = [];
                foreach ($orderPerson as $k=>$v) {
                    for($i=0;$i<=$v['person_num'];$i++){
                        $customerArr[] = ['customer_type_rate'=>intval($v['person_id'])];
                    }
                }

                $f_xing = !empty($post['contact_xing'])?$post['contact_xing']:'';//xing
                $f_ming = !empty($post['contact_ming'])?$post['contact_ming']:'';//ming

                $params = [
                    'voucher_number'=>$kbx_order['orderNo'],
                    'userinfo'=>[
                        'name'=>$f_ming."".$f_xing,
                        'phone'=>!empty($post['phone'])?$post['phone']:null,
                        'email'=>!empty($post['e_mail'])?$post['e_mail']:null,
                    ],
                    'customers'=>$customerArr,
                ];

                //验证预订
                $fare_availability = $Fareharbor->bookings_validate($fare_goods['company'],$kbx_order['specsId'],$params);

                if(!empty($fare_availability['error'])){
                    $shu=[
                        'code'=>isset($fare_availability['code'])?$fare_availability['code']:400,
                        'msg'=>$fare_availability['error'],
                    ];
                    return json_encode($shu);
                }

                if(!isset($fare_availability['is_bookable']) || $fare_availability['is_bookable']==false){
                    $shu=[
                        'code'=>400,
                        'msg'=>"该次预订商家显示不可用，请取消后重新下单",
                    ];
                    return json_encode($shu);
                }
            }

            //调用计算价格
            //判断如果有msg 就抛出错误
            if (!empty($post['coupon_id'])){
                $arr=[
                    'order_id' =>$order_no,
                    'coupon_id'=>$post['coupon_id'],
                    'member_id'=>$post['member_id'],
                    'coupon_type'=>$post['coupon_type'],
                    'type'=>1,
                    'original_money'=>$kbx_order['payments']['originalMoney'],
                ];
                $jiage= $this->price($arr);
            }

            if (!empty($jiage['msg'])) return json_encode(['code'=>101, 'msg'=>$jiage['msg']]);

            $code=db('goods')->where('goods_id',$kbx_order['goods']['goodsId'])->find();
            $pos=$kbx_order['itinerary']['orderPerson'];
            $data['order']=$order_no;//订单流水
            $data['time']=date('Y-m-d',strtotime($kbx_order['itinerary']['travelDate']));
            $data['code']=$code['code'];  //产品code
            $data['tourGradeCode']=$kbx_order['goods']['grade'];  //旅游等级 商品详情获取 tourGrades
            $data['orderuser']=[  //下单人信息- -
                'firstname'=>$post['contact_ming'],  //名
                'surname'=>$post['contact_xing'],  //姓
                'Phone'=>$post['phone'], //必填
                'email'=>$post['e_mail'],
                'title'=>'',
            ];
            foreach ($pos as $v){
                $datas['bandid'][$v['person_id']]= $v['person_num'];
            }
            if ($kbx_order['orderAscription']==2||$kbx_order['orderAscription']==3){
                $ds=json_decode($post['person'],true);
                foreach ($ds as $v){
                    if ( $v['person_id']==1){
                        foreach ($v['people'] as $l=>$h){
                            if ($l==0){
                                $tempList=[  //领班人/领头人
                                    'leadTraveller'=>true,
                                    'bandId'=>$v['person_id'],
                                    'firstname'=>$h['ming'],
                                    'surname'=>$h['xing'],
                                    'title'=>'',//称呼
                                    'cellPhoneCountryCode'=>$h['phoneCode'],//手机国家码
                                    'cellPhone'=>$h['phone'],//手机
                                ];
                            }else{
                                $tempList=[  //领班人/领头人
                                    'leadTraveller'=>false,
                                    'bandId'=>$v['person_id'],
                                    'firstname'=>$h['ming'],
                                    'surname'=>$h['xing'],
                                    'title'=>'',//称呼
                                    'cellPhoneCountryCode'=>'',//手机国家码
                                    'cellPhone'=>'',//手机
                                ];
                            }
                            $data['bandiduser'][]=$tempList;
                        }
                    }else{
                        $tempList = [];
                        foreach ($v['people'] as $l=>$h) {
                            $tempList = [  //领班人/领头人
                                'leadTraveller' => false,
                                'bandId' => $v['person_id'],
                                'firstname'=>$h['ming'],
                                'surname'=>$h['xing'],
                                'title' => '',//称呼
                                'cellPhoneCountryCode' => '',//手机国家码
                                'cellPhone' => '',//手机
                            ];
                        }
                        $data['bandiduser'][]=$tempList;
                    }
                }
            }
        }

        $order_status=1;
        if (isset($post['coupon_id']) && $post['coupon_id']!==''&& $post['fold_money']==0){
            $order_status=2;
        }

        Db::startTrans();
        try{
            $coupon= !empty($post['coupon_id'])?$post['coupon_id']:0;
            if ($coupon!=0 && $post['coupon_type']=='OWN'){
                $usetime=time();
                db('coupondetails')->where('id',$coupon)->update([
                    'usestatus'=>1,'usetime'=>$usetime
                ]);
                //追加写入记录表
                $log_list=[
                    'coupon_id'=>$coupon,
                    'member_id'=>$post['member_id'],
                    'order_id'=>$post['order_id'],
                    'createtime'=>$usetime,
                ];
                Db::name('coupon_log')->insert($log_list);
            }

            //写表
            //判断订单类型，决定是否调用订单系统接口，存订单系统mongo库还是本系统mysql
            if(in_array($orderType,array("Vehicle","Custom","Other","Rental_Device","Price_Gap","Self_Drive","Personal_Tailor","Subscription")))
            {//mysql
                $updateArr = [
                    'finished_condition'=>0,
                    'wechat_number'=>!empty($post['wechat_number'])?$post['wechat_number']:null,//微信号
                    'phone'=>!empty($post['phone'])?$post['phone']:null,//手机号
                    'fold_money'=>!empty($jiage['discountprice'])?$jiage['discountprice']:$post['fold_money'],//折扣后的金额
                    'updatetime'=>time(),//更新时间
                    'cost_ticket_id'=>$coupon,//使用优惠券的id
                    'contact_xing'=>!empty($post['contact_xing'])?$post['contact_xing']:null,//xing
                    'contact_ming'=>!empty($post['contact_ming'])?$post['contact_ming']:null,//ming
                    'remarks'=>!empty($post['remarks'])?$post['remarks']:null,//备注
                    'e_mail'=>!empty($post['e_mail'])?$post['e_mail']:null,//邮箱
                    'order_subsidiary'=>!empty($data)?json_encode($data):null,//随行人员
                    'coupon_type'=>!empty($post['coupon_type'])?$post['coupon_type']:null,//优惠券类型
                    'order_status'=>$order_status,//随行人员
                    'bookingQuestionAnswers'=>!empty($post['bookingQuestionAnswers'])?$post['bookingQuestionAnswers']:null,//预约问题
                    'serve_address'=>!empty($post['serve_address'])?$post['serve_address']:null,//接待地址
                ];
                $m->where('order_id',$post['order_id'])->Update($updateArr);

            }else{//mongo
                //调用订单系统接口   更新订单数据
                //组装数据
                $postXing = !empty($post['contact_xing'])?$post['contact_xing']:'';//xing
                $postMing = !empty($post['contact_ming'])?$post['contact_ming']:'';//ming
                $postName = $postXing.$postMing;
                $postUpdateArr = [
                    'id'=>$order_id,
                    'isSubmit'=>'submit',
                    'contact'=>array(
                        'serveAddress'=>!empty($post['serve_address'])?$post['serve_address']:null,//接待地址
                        'remarks'=>!empty($post['remarks'])?$post['remarks']:null,//备注
                        'wechat'=>!empty($post['wechat_number'])?$post['wechat_number']:null,//微信号
                        'phone'=>!empty($post['phone'])?$post['phone']:null,//手机号
                        'name'=>$postName,//姓名
                        'email'=>!empty($post['e_mail'])?$post['e_mail']:null,//邮箱
                    ),
                    'payments'=>array(
                        'costTicketId'=>$coupon,//使用优惠券的id
                        'couponType'=>!empty($post['coupon_type'])?$post['coupon_type']:null,//优惠券类型
                        'foldMoney'=>!empty($jiage['discountprice'])?$jiage['discountprice']:$post['fold_money'],//折扣后的金额
                    ),
                    'itinerary'=>array(
                        'orderSubsidiary'=>!empty($data) ? $data :null,//随行人员
                    ),
                    'details'=>array(
                        'bookingQuestionAnswers'=>!empty($post['bookingQuestionAnswers'])?$post['bookingQuestionAnswers']:null,//预约问题
                    ),
                    'statusPhp'=>array(
                        'orderStatus'=>$order_status,
                        'finishedCondition'=>0,
                    ),
                    'status'=>array(
                        'orderStatus'=>$this->statusArr[$order_status]['orderStatus'],
                        'paymentStatus'=>$this->statusArr[$order_status]['paymentStatus'],
                    ),
                ];
                $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);

                $log[]=[
                    '订单系统API：更新submit信息'=>json_encode($postUpdateArr),
                    'res'=>$update_res
                ];
                Log::record($log);
            }

            Db::commit();

            //折扣后需要付款的金额
            $shu_fold_money = !empty($jiage['discountprice'])?$jiage['discountprice']:$post['fold_money'];

            //汇率
            $exchangeArr = Db::name("exchange")->select();
            if(!empty($exchangeArr)){
                $moneyArr = array();
                foreach ($exchangeArr as $k=>$v) {
                    $v_money = $shu_fold_money/$v['exchange_rate'];
                    $v_money = ceil($v_money*100)/100;
                    $moneyArr[] = array("code"=>$v['currency_code'],"money"=>$v_money);
                }
            }
            $moneyArr[] = array("code"=>"CNY","money"=>$shu_fold_money);

            $shu=[
                'code'=>0,
                'msg'=>'订单ok',
                'moneyArr'=>$moneyArr,
                'fold_money'=>$shu_fold_money,//折扣后的金额
            ];
        } catch (\Exception $e) {
            Db::rollback();
            $shu=[
                'code'=>101,
                'msg'=>'失败',
                'error'=>$e->getMessage()
            ];
        }

        $log[]=[
            'submit返回'.$order_no => $shu,
        ];
        Log::record($log);

        if (!empty($post['coupon_id'])){
            if ($jiage['discountprice']==0){
                $Notify = new Notify();
                //获取订单信息
                $kbx_order = $KbxOrder->kbx_order_by_no($order_no);
                //调用短信邮箱
                if(!empty($kbx_order['typeSource'])){
                    if($kbx_order['typeSource']=='viator'){
                        $order_info=$data;
                        $Viator = new Viator();
                        $order_info=$Viator->object_array($order_info);
                        //预约问题
                        $order_question = '';
                        $bookingQ = !empty($post['bookingQuestionAnswers'])?$post['bookingQuestionAnswers']:null;
                        if(!empty($bookingQ)){
                            $order_question=json_decode($bookingQ);
                            $order_question=$Viator->object_array($order_question);
                        }
                        $dat= $Viator->bookingUser($order_info,$order_question,$kbx_order['id'],$kbx_order['orderType']);
                        if ($dat['code']==001){
                            //下单失败
                            // 退款
                            $Kbxcoupon=  new Kbxcoupon();
                            if ($post['coupon_type']=='KBX'){
                                $aa = $Kbxcoupon->refundCashCoupon($post['member_id'], $coupon, $order_no);
                            }else{
                                $aa = db('coupondetails')->where('id',$coupon)->update(['usestatus'=>0]);
                            }
                            if (empty($aa)|| $aa==true){
                                //订单系统  更新order数据
                                $postUpdateArr = [
                                    'id'=>$order_id,
                                    'statusPhp'=>array(
                                        'orderStatus'=>8,
                                    ),
                                    'status'=>array(//状态（新）
                                        'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                        'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                    ),
                                    'refund'=>array(
                                        'refundMoney'=>$kbx_order['payments']['foldMoney'],
                                        'refundStatus'=>2,
                                    ),
                                ];
                                $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                                $log[]=[
                                    '订单系统API：退款成功'=>json_encode($postUpdateArr),
                                    'res'=>$update_res
                                ];
                                Log::record($log);

                                if($update_res){
                                    $md=Db::name('Accounts')->insert([
                                        'member_id'=>$post['member_id'],
                                        'accounts_money'=>$kbx_order['payments']['foldMoney'],
                                        'business_way'=>4,
                                        'creattime'=>date('YmdHis',time())
                                    ]);
                                }
                            }else{
                                $title='自动退款失败';
                                $res='订单号为'.$order_no.'的订单，退款失败，原因为'.$aa.'请尽快处理！';
                                $Notify->kbxemailcode($title,$res,'david@kuaibangxing.com');
                                $shu=[
                                    'code'=>101,
                                    'msg'=>'自动退款失败',
                                ];

                                return json_encode($shu) ;
                            }
                            // 下单 失败短信通知
                            $title='预约失败';
                            $res='【快帮行】您好，您的订单预订失败，退款已原路返回您的微信账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                            $Notify->kbxemailcode($title,$res,$post['e_mail']);
                            $shu=[
                                'code'=>101,
                                'msg'=>'预约失败',
                            ];

                            return json_encode($shu) ;
                        }
                    }elseif($kbx_order['typeSource']=='fareharbor'){//fareharbor订单
                        $Fareharbor = new Fareharbor();
                        $goods = db("goods")->where("goods_id",$kbx_order['goods']['goodsId'])->field("source_id")->find();
                        $fare_goods = db('fareharbor_goods')->where('fare_goods_id',$goods['source_id'])->find();

                        $orderPerson = $kbx_order['itinerary']['orderPerson'];

                        $customerArr = [];
                        foreach ($orderPerson as $k=>$v) {
                            for($i=0;$i<=$v['person_num'];$i++){
                                $customerArr[] = ['customer_type_rate'=>intval($v['person_id'])];
                            }
                        }

                        $params = [
                            'voucher_number'=>$kbx_order['orderNo'],
                            'userinfo'=>[
                                'name'=>$kbx_order['contact']['name'],
                                'phone'=>$kbx_order['contact']['phone'],
                                'email'=>$kbx_order['contact']['email'],
                            ],
                            'customers'=>$customerArr,
                        ];

                        //真实下单
                        $booking_data = $Fareharbor->bookings($fare_goods['company'],$kbx_order['specsId'],$params);
                        trace('fareharbor下单返回数据：'.json_encode($booking_data));
                        if(!empty($booking_data['error'])){
                            //下单失败
                            // 退款
                            $Kbxcoupon=  new Kbxcoupon();
                            if ($post['coupon_type']=='KBX'){
                                $aa = $Kbxcoupon->refundCashCoupon($post['member_id'], $coupon, $order_no);
                            }else{
                                $aa = db('coupondetails')->where('id',$coupon)->update(['usestatus'=>0]);
                            }
                            if (empty($aa)|| $aa==true){
                                //订单系统  更新order数据
                                $postUpdateArr = [
                                    'id'=>$order_id,
                                    'statusPhp'=>array(
                                        'orderStatus'=>8,
                                    ),
                                    'status'=>array(//状态（新）
                                        'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                        'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                    ),
                                    'refund'=>array(
                                        'refundMoney'=>$kbx_order['payments']['foldMoney'],
                                        'refundStatus'=>2,
                                    ),
                                ];
                                $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                                $log[]=[
                                    '订单系统API：退款成功'=>json_encode($postUpdateArr),
                                    'res'=>$update_res
                                ];
                                Log::record($log);

                                if($update_res){
                                    Db::name('Accounts')->insert([
                                        'member_id'=>$post['member_id'],
                                        'accounts_money'=>$kbx_order['payments']['foldMoney'],
                                        'business_way'=>4,
                                        'creattime'=>date('YmdHis',time())
                                    ]);
                                }
                            }else{
                                $title='自动退款失败';
                                $res='订单号为'.$order_no.'的订单，退款失败，原因为'.$aa.'请尽快处理！';
                                $Notify->kbxemailcode($title,$res,'david@kuaibangxing.com');
                                $shu=[
                                    'code'=>101,
                                    'msg'=>'自动退款失败',
                                ];

                                return json_encode($shu) ;
                            }
                            // 下单 失败短信通知
                            $title='预约失败';
                            $res='【快帮行】您好，您的订单预订失败，退款已原路返回您的微信账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                            $Notify->kbxemailcode($title,$res,$post['e_mail']);
                            $shu=[
                                'code'=>101,
                                'msg'=>'预约失败',
                            ];

                            return json_encode($shu) ;
                        }else{
                            //下单成功
                            $postUpdateArr = [
                                'id'=>$kbx_order['id'],
                                'details'=>$booking_data['booking'],
                                'supplier'=>array(
                                    'cost'=>array(
                                        'currency'=>'USD',
                                        'amount'=>$booking_data['booking']['amount_paid']/100
                                    )
                                ),
                                'detailsFrom'=>'fareharbor',
                            ];
                            $KbxOrder = new KbxOrder();
                            $update_res = $KbxOrder->kbx_operate_order($kbx_order['orderType'],$postUpdateArr);

                            $log[]=[
                                '订单系统API：fareharbor下单数据更新'=>json_encode($postUpdateArr),
                                'res'=>$update_res,
                                'type'=>"coupon"
                            ];
                            Log::record($log);
                        }
                    }
                }

                //判断订单属于mongo库还是mysql库
                if(in_array($orderType,array("Vehicle","Custom","Other","Rental_Device","Price_Gap","Self_Drive","Personal_Tailor","Subscription"))){
                    $od=$m->where('order_id',$post['order_id'])->find();
                    Db::name('Accounts')->insert([
                        'member_id'=>$post['member_id'],
                        'accounts_money'=>!empty($jiage['discountprice'])?$jiage['discountprice']:$post['fold_money'],
                        'business_way'=>1,
                        'creattime'=>date('YmdHis',time())
                    ]);
                    $orderDate = array(
                        'goods_id'=>$od['goods_id'],
                        'member_id'=>$post['member_id'],
                        'speedstatus'=>$od['speedstatus'],
                        'order_no'=>$order_no,
                        'travel_date'=>date('Y-m-d',strtotime($od['travel_date'])),
                        'e_mail'=>$post['e_mail'],
                        'phone'=>$post['phone']
                    );
                }else{//mongo
                    Db::name('Accounts')->insert([
                        'member_id'=>$post['member_id'],
                        'accounts_money'=>$kbx_order['payments']['foldMoney'],
                        'business_way'=>1,
                        'creattime'=>date('YmdHis',time())
                    ]);
                    $orderDate = array(
                        'goods_id'=>$kbx_order['goods']['goodsId'],
                        'member_id'=>$kbx_order['booker']['memberId'],
                        'speedstatus'=>$kbx_order['speedStatus'],
                        'order_no'=>$order_no,
                        'travel_date'=>date('Y-m-d',strtotime($kbx_order['itinerary']['travelDate'])),
                        'e_mail'=>$post['e_mail'],
                        'phone'=>$kbx_order['contact']['phone']
                    );
                }

                $Notify->gyouxiang($orderDate);
                $Notify->youxiang($orderDate);

                //立即确认的才发送短信  发送凭证
                if(isset($kbx_order['speedStatus']) && $kbx_order['speedStatus']==0){
                    $Notify->duanxin($orderDate);
                    if(isset($kbx_order['typeSource']) && $kbx_order['typeSource']=='viator'){
                        $title=$order_no;
                        $voucherUrl = "<p><b><a href='https://prelive.viatorapi.viator.com/service/merchant/voucher.jspa?code=".$dat['data']['voucherKey']."&embedResources=false'>点击下载凭证</a></b></p><br>";
                        $Notify->kbxemailcode($title,$voucherUrl,'david@kuaibangxing.com');
                    }
                }
            }
        }
        //已支付完成算销量
        if($order_status==2){
            //写入销量
            $goodssales=Db::name('goods')->where(['goods_id'=>$goods_id])->find()['goodssales'];
            $goodssales=(int)$goodssales + 1;
            Db::name('goods')->where(['goods_id'=>$goods_id])->update(['goodssales'=>$goodssales]);
        }

        $log[]=[
            'submit结束--'.$order_no => $shu,
        ];
        Log::record($log);

        return json_encode($shu);
    }


    //计算价格
    public function price($post=['order_id'=>'','coupon_id'=>'','member_id'=>'','coupon_type'=>'','type'=>'','original_money'=>'']){
        if (empty($post)||!is_array($post)) return json_encode(['msg'=>'参数错误请求数据为空','code'=>'101']);
        if (empty($post['order_id'])||empty($post['order_type'])||empty($post['coupon_id'])||empty($post['member_id'])||empty($post['coupon_type'])) json_encode(['msg'=>'参数错误请求数据为空','code'=>'101']);

        if($post['type']==1){//mongo
            $order_original_money = $post['original_money'];
            $order_fold_money = $order_original_money;
            $order_no = $post['order_id'];
        }else{//mysql
            $order=db('order')->where('order_id',$post['order_id'])->find();
            $order_original_money= $order['original_money'];
            $order_fold_money= $order['fold_money'];
            $order_no = $order['order_no'];
        }

        $money=[];
        $money1='';
        if (!empty($order['coupon_type'])){
            $money=[
                'yuanjia'=>$order_original_money,
                'discountprice'=>$order_fold_money,
            ];
            return $money;
        }
        if ($post['coupon_type']=='OWN'){
            $coupon=db('coupondetails')
                ->alias('a')
                ->where('a.id',$post['coupon_id'])
                ->join('coupon b','b.coupon_id=a.coupon_id')
                ->find();
            if ($order_original_money>=$coupon['coupon_usecondition']){
                if ($coupon['coupon_types']==1){
                    $money1=ceil($order_original_money*$coupon['coupon_discount']);
                }
                if ($coupon['coupon_types']==2){
                    $money1=ceil($order_original_money-$coupon['coupon_discount']);
                    $money1 = $money1>=0 ? $money1 : 0;
                }
                $money=[
                    'yuanjia'=>$order_original_money,
                    'discountprice'=>$money1,
                ];
            }else{
                return ['msg'=>'不满足旅行红包使用条件','code'=>'101'];
            }
        }else if ($post['coupon_type']=='KBX'){
            $KBX = new Kbxcoupon();
            $da= $KBX->useCashCoupon($post['member_id'],$post['coupon_id'],$order_original_money,$order_no);
            $da=json_decode($da,true);

            $money=[
                'yuanjia'=>$order_original_money,
                'discountprice'=>$da['left'],
            ];
            if (!empty($da['msg'])) return ['msg'=>$da['msg'],'code'=>101];
        }

        return $money;
    }


    //价格退回
    public function refund(){
        $post= input('post.');
        if (empty($post)||!is_array($post)) return json_encode(['msg'=>'参数错误请求数据为空','code'=>'101']);
        if (empty($post['order_id'])||empty($post['coupon_id'])||empty($post['member_id'])||empty($post['coupon_type'])) json_encode(['msg'=>'参数错误请求数据为空','code'=>'101']);
        $order=db('order')->where('order_id',$post['order_id'])->find();

         if ($post['coupon_type']=='KBX'){
            $KBX=  new Kbxcoupon();
            $da= $KBX->refundCashCoupon($post['member_id'],$post['coupon_id'],$order['order_no']);
            $da=json_decode($da,true);

            $money=[
                'yuanjia'=>$order['original_money'],
                'discountprice'=>$da['left'],
            ];
             if (!empty($da['msg'])) return json_encode(['msg'=>$da['msg'],'code'=>101]);
             return json_encode(['msg'=>'ok','code'=>0]);
        }
    }

    //定制行程下单
    public function createCustomMadeOrder()
    {
        $post = request()->post();
        $member_id = $post['member_id']??0;
        $member = db('member')->where('member_id',$post['member_id'])->find();
        if(empty($member_id) || empty($member)){
            return json_encode(['code'=>101,'msg'=>'请先登陆']);
        }
        //记录用户信息
        $user_xing = $post['contact_xing']??"";
        $user_ming = $post['contact_ming']??"";
        $phone = $post['phone']??"";
        $wechat = $post['wechat']??"";
        $email = $post['e_mail']??"";
        if(empty($user_ming)) return json_encode(['code'=>101,'msg'=>'请填写姓名']);
        if(empty($phone)) return json_encode(['code'=>101,'msg'=>'请填写预定手机']);
        //if(empty($email)) return json_encode(['code'=>101,'msg'=>'请填写预定邮箱']);

        $tripid = $post['trip_id']??0;
        if(empty($tripid)) return json_encode(['code'=>101,'msg'=>'您的定制行程存在问题']);
        //用户直接下单的状态
        $statusData = [
            'statusPhp'=>[
                'orderStatus'=>1,//待支付状态
                'finishedCondition'=>0,//表单已完善
            ]
        ];
        $trip = (new TripApi())->getAutoCreateOrderData($tripid,$member,$statusData);
        //需要中转订单模型
        //$trip = json_decode($trip,true);
//        if($trip['isLocked']==1){
//            return json_encode(['code'=>101,'msg'=>'该行程已锁定！']);
//        }

        if($trip['totalSalePrice']<=0){
            return json_encode(['code'=>101,'msg'=>'该行程支付金额必须大于0！']);
        }
        //接受用户信息进行封装
        $user_name = $user_xing.$user_ming;
        $trip['contact']['name'] = $user_name?:$trip['contact']['name'];
        $trip['contact']['email'] = $email?:$trip['contact']['email'];
        $trip['contact']['wechat'] = $wechat?:$trip['contact']['wechat'];
        $trip['contact']['phone'] = $phone?:$trip['contact']['phone'];
        //是否包含区号
        if(!empty($trip['contact']['phone'])){
            $trip['contact']['phone'] = strpos($trip['contact']['phone'],'+')!==false?$trip['contact']['phone']:"+86".$trip['contact']['phone'];
        }
        $result = (new TripApi())->pushCustomMadeOrder($trip,$member_id);
        if(!is_array($result)){
            return json_encode(['code'=>101,'msg'=>$result]);
        }else{
            return json_encode(['code'=>200,'msg'=>'下单成功','data'=>$result]);
        }
    }

}